/***/
class KPromise {
	static PENDING = 'PENDING'
	static RESOLVED = 'RESOLVED'
	static REJECTED = 'REJECTED'
	constructor(handler) {
		if(typeof handler !== 'function') {
			throw new TypeError('Promise resolver undefined is not a function')
		}
		this.resolvedQueues = []
		this.rejectedQueues = []
		this.status = KPromise.PENDING
		this.value = null
		handler(this._resolve.bind(this),this._reject.bind(this))
	}
	_resolve(res){
		// 放在微任务异步事件内，使得resolve内的代码执行顺序优于宏任务setTimeout
		this.value = res
		window.addEventListener('message',_ => {
			if(this.status !== KPromise.PENDING) {
				return
			}
			this.status= KPromise.RESOLVED
			let handler
			while(handler = this.resolvedQueues.shift()) {
				handler(this.value)
			}
		})
		window.postMessage('')
		
	}
	_reject(err){
		window.addEventListener('message', _ => {
			if(this.status !== KPromise.PENDING) { // 状态只能被修改一次
				return
			}
			this.status = KPromise.REJECTED
			let handler
			while(handler = this.rejectedQueues.shift()) {
				handler(err)
			}
		})

		window.postMessage('')
	}
	then(resolvedHandler,rejectedHandler) {
		// resolvedHandler() // 不能直接调用
		// 完成事件注册
		/*
		 (这样做解决了then的一次调用,但是连续调用不能实现)
		this.resolvedQueues.push(resolvedHandler)
		this.rejectedQueues.push(rejectedHandler)*/
		// 返回一个新的KPromise对象,并且要先执行
		return new KPromise( (resolve,reject) => {  
			// 完成事件注册,注册的事件里先执行第一次then传入的函数,然后执行本次KPomise传入的事件
			this.resolvedQueues.push(_reslveFn)
			this.rejectedQueues.push(_rejectFn)
			function _reslveFn(val) {
				const result = resolvedHandler(val)
				// 只考虑KPomise和基本数据类型的结果
				if(result instanceof KPromise) {
					result.then()
				}else {

				}
				resolve(result)
			}
			function _rejectFn(error) {
				const result = rejectedHandler(error)
				reject(result)
			}
		} )
	}
}